import {
	VPage,
	onLoad,
	onReady,
	onShareAppMessage
} from 'v3-mini';
import {
	system,
	resetRatio
} from '../../utils/global'
import util from '../../utils/util';
import Canvas from '../../utils/canvas';

VPage({
	setup(props, context) {
		// methods
		function getSystemInfo() {
			util.ajax({
				url: 'ruler/get',
				data: {
					name: wx.getSystemInfoSync().model
				},
				success(res) {
					system.width = res.width
					system.height = res.height
					system.diagonal = res.diagonal
					resetRatio()

					wx.setStorageSync('m-width', system.width)
					wx.setStorageSync('m-height', system.height)
					wx.setStorageSync('m-diagonal', system.diagonal)
				},
				async fail(res) {
					await util.alert(res.data ? res.data.message : res.errMsg);
					wx.navigateTo({
						url: '/pages/setting/setting',
					})
				}
			})
		}
		let container

		function touchstart(e) {
			container && container.touchstart(e)
		}

		function touchmove(e) {
			container && container.touchmove(e)
		}

		function touchend(e) {
			container && container.touchend(e)
		}

		function createCanvas() {
			const query = wx.createSelectorQuery()
			query.select('#container')
				.fields({
					node: true,
					size: true
				})
				.exec((res) => {
					if (res[0]) {
						const canvas = res[0].node
						container = new Canvas(canvas, res[0].width, res[0].height)
					}
				})
		}

		// lifecycle
		onLoad(() => {
			wx.removeStorageSync('width')
			wx.removeStorageSync('height')
			wx.removeStorageSync('diagonal')
			if (!wx.getStorageSync('m-width')) {
				getSystemInfo()
			}
		})
		onReady(createCanvas)


		onShareAppMessage(() => {
			return {
				title: '尺子测量工具'
			}
		})

		return {
			touchstart,
			touchmove,
			touchend,
		}
	},
})